﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace KATS_Client
{
    /// <summary>
    /// A buffered file writer
    /// </summary>
    public class BufferedFileWrite : IDisposable
    {
        /// <summary>The size of the buffer</summary>
        int bufferSize;

        /// <summary>The output location</summary>
        BinaryWriter fileOutput = null;

        /// <summary>The buffer location</summary>
        MemoryStream storage;

        public BufferedFileWrite(int BufferSize, BinaryWriter output)
        {
            this.bufferSize = BufferSize;
            this.fileOutput = output;
            storage = new MemoryStream(this.bufferSize);
        }

        /// <summary>
        /// Write these bytes to the buffer
        /// </summary>
        /// <param name="data"></param>
        public void Write(byte[] data)
        {
            if (data.Length == 0)
                return;
            if (storage.Position + data.Length > bufferSize)
            {
                // then there will be too much data in the buffer
                // so write out all the current buffer
                Flush();
            }
            storage.Write(data, 0, data.Length);
        }

        /// <summary>
        /// Empty the buffer to the harddrive
        /// </summary>
        public void Flush()
        {
            byte[] output = storage.ToArray();
            if (output.Length == 0)
                return;

            fileOutput.Write(output);
            storage.Dispose();
            storage = null;
            storage = new MemoryStream(bufferSize);
        }

        /// <summary>
        /// Dispose of this object
        /// </summary>
        public void Dispose()
        {
            if (fileOutput != null)
            {
                Flush();
                fileOutput.Flush();
            }

            if (storage != null)
            {
                storage.Close();
                storage = null;
            }

            if (fileOutput != null)
            {
                fileOutput.Close();
                fileOutput = null;
            }
        }
    }
}
